﻿using System;
using System.Data;
using System.Data.Odbc;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace MedicinskiUslugi {

	public partial class frmImportdbf : Form {

		public frmImportdbf() {
			InitializeComponent();
		}

		public DataTable dataFromDb = new DataTable();
		public bool vneseno = false;
		public OdbcConnection dbConnection = new OdbcConnection();
		public string EEdinica;

		private void button1_Click( object sender, EventArgs e ) {
			FolderBrowserDialog opendbf = new FolderBrowserDialog();
			opendbf.ShowDialog();
			dbConnection.ConnectionString = @"Driver={Microsoft Visual FoxPro Driver};SourceType=DBF;SourceDB=" + opendbf.SelectedPath + ";Exclusive=No; Collate=Machine;NULL=NO;DELETED=NO;BACKGROUNDFETCH=NO;";
			if ( opendbf.SelectedPath.Length > 1 ) {
				string[] filePaths = Directory.GetFiles( opendbf.SelectedPath, "*.dbf", SearchOption.TopDirectoryOnly );
				foreach ( string item in filePaths ) {
					ListOfFiles.Items.Add( item );
				}
			}
			btnOtvori.Enabled = false;
		}

		private void btnVnesi_Click( object sender, EventArgs e ) {
			vneseno = true;
			this.Close();
		}

		private void ListOfFiles_SelectedIndexChanged( object sender, EventArgs e ) {
			if ( ListOfFiles.SelectedItems.Count == 1 ) {
				try {
					dbConnection.Open();
					string imeNaDBF = ListOfFiles.SelectedItems[0].Text.Split( @"\".ToCharArray().First() ).Last().ToString();
					OdbcCommand com = new OdbcCommand( "Select * from " + imeNaDBF, dbConnection );
					dataFromDb.Load( com.ExecuteReader() );
					dbConnection.Close();

					label1.Text = "Економска Единица: " + imeNaDBF.Substring( 1, 2 );
					label2.Text = "Број на редови: " + dataFromDb.Rows.Count;
					FileInfo info = new FileInfo( ListOfFiles.SelectedItems[0].Text );
					label3.Text = "Датум на фајлот: " + info.CreationTime.Date.ToShortDateString();
					label4.Text = "Големина на фајлот: " + info.Length.ToString();
					decimal participacija = Convert.ToDecimal( dataFromDb.Compute( "Sum( PAR_OBS )", "" ) );
					decimal cena = Convert.ToDecimal( dataFromDb.Compute( "Sum( CEN_OBS )", "" ) );
					label5.Text = "Сума на партиципација: " + participacija.ToString();
					label6.Text = "Сума на цена: " + cena.ToString();
					label7.Text = "Сума на Вкупно: " + ( participacija + cena ).ToString();
					label8.Text = "Сума на Kоличина: " + dataFromDb.Compute( "Sum( KOL_OBS )", "" ).ToString();
					EEdinica = imeNaDBF.Substring( 1, 2 );
				}
				catch ( Exception ex ) {
					MessageBox.Show( ex.Message );
				}
			}
		}
	}
}